<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发货修改装箱</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
            padding-bottom: 90px;
            margin: 0;
            min-height: 100vh;
            position: relative;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
        }
        .header h1 {
            font-size: 24px;
            color: #333;
        }
        .info-area {
            background-color: #fff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .info-label {
            color: #666;
            font-size: 14px;
        }
        .info-value {
            color: #333;
            font-weight: bold;
            font-size: 14px;
        }
        .scan-area {
            background-color: #fff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .scan-group {
            margin-bottom: 15px;
        }
        .scan-input {
            width: 100%;
            padding: 10px;
            font-size: 18px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .list-area {
            background-color: #fff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            max-height: 400px;
            overflow-y: auto;
        }
        .list-header {
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            padding: 10px 0;
            border-bottom: 1px solid #ddd;
            font-weight: bold;
        }
        .list-item {
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .button-area {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            padding: 15px 20px;
            background-color: #fff;
            z-index: 100;
        }
        .button {
            padding: 15px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
        }
        .clear-button {
            background-color: #6c757d;
            color: #fff;
        }
        .confirm-button {
            background-color: #28a745;
            color: #fff;
        }
        .alert-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .alert-content {
            background-color: #333;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
            color: #fff;
            width: 200px;
            position: relative;
        }
        .alert-icon {
            width: 50px;
            height: 50px;
            background-color: #fff;
            border-radius: 50%;
            margin: 0 auto 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30px;
            color: #333;
        }
        .alert-text {
            font-size: 16px;
            line-height: 1.4;
        }
        .back-button {
            position: fixed;
            top: 20px;
            left: 20px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 8px 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            font-size: 16px;
            color: #333;
            z-index: 100;
        }
        .back-button:before {
            content: "←";
            margin-right: 5px;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <button class="back-button" onclick="history.back()">返回</button>
    <div class="container">
        <div class="header">
            <h1 id="pageTitle">发货修改装箱</h1>
        </div>
        <div class="scan-area">
            <div class="scan-group">
                <input type="text" class="scan-input" id="boxCodeInput" placeholder="请扫描箱码">
            </div>
            <div class="scan-group">
                <input type="text" class="scan-input" id="skuInput" placeholder="请扫描鞋子条码">
            </div>
        </div>
        <div class="list-area">
            <div class="list-header">
                <div>条码</div>
                <div>货号/颜色/尺码</div>
                <div>数量</div>
            </div>
            <div id="skuList"></div>
        </div>
        <div class="button-area">
            <button class="button clear-button" onclick="clearScannedItems()">清空已扫明细</button>
            <button class="button confirm-button" onclick="confirmBox()">确认装箱</button>
        </div>
    </div>

    <div class="alert-overlay" id="alertOverlay">
        <div class="alert-content">
            <div class="alert-icon">!</div>
            <div class="alert-text"></div>
        </div>
    </div>

    <script>
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const mode = urlParams.get('mode');
        const planCode = urlParams.get('code');
        
        // 存储扫描的商品数据
        let scannedItems = {};
        let currentBoxCode = '';
        
        // 模拟数据 - 实际应该从后端获取
        const planData = {
            "plan_code": "PN20250428002",
            "purchase_order_code": "ST20250423001",
            "SPU": "ST1839",
            "bound_box_codes": ["CD250423000001", "CD250423000002"],
            "valid_skus": [
                {
                    "fnsku": "X001P67ABJ",
                    "chinese_sku": "ST1839/灰色/8",
                    "order_quantity": 100  // 采购单下单量
                },
                {
                    "fnsku": "X001P58RN9",
                    "chinese_sku": "ST1839/白色/9",
                    "order_quantity": 200
                }
            ],
            "other_boxes": [  // 入库计划内其他箱子的内容
                {
                    "box_code": "CD250423000003",
                    "sku_detail": [
                        {
                            "fnsku": "X001P67ABJ",
                            "quantity":10
                        },
                        {
                            "fnsku": "X001P58RN9",
                            "quantity": 44
                        }
                    ]
                }
            ],
            "applied_quantities": {  // 采购单已申请量
                "X001P67ABJ": 80,
                "X001P58RN9": 150
            }
        };

        // 初始化页面
        function initPage() {
            // 设置页面标题
            document.getElementById('pageTitle').textContent = 
                mode === 'repack' ? '重新装箱' : '新增箱子';
            
            // 设置基本信息
            document.getElementById('planCode').textContent = planData.plan_code;
            document.getElementById('purchaseCode').textContent = planData.purchase_order_code;
            document.getElementById('spu').textContent = planData.SPU;
        }

        // 验证箱码
        function validateBoxCode(code) {
            const regex = /^CD\d{12}$/;
            if (!regex.test(code)) {
                return false;
            }

            if (mode === 'repack') {
                // 重新装箱模式：箱码必须是已绑定的箱码
                return planData.bound_box_codes.includes(code);
            } else {
                // 新增箱子模式：验证是否为空箱
                // 这里应该调用后端API验证，现在用随机模拟
                return Math.random() >= 0.4;
            }
        }

        // 验证SKU
        function validateSku(fnsku) {
            return planData.valid_skus.some(item => item.fnsku === fnsku);
        }

        // 获取中文SKU
        function getChineseSku(fnsku) {
            const sku = planData.valid_skus.find(item => item.fnsku === fnsku);
            return sku ? sku.chinese_sku : null;
        }

        // 显示提示
        function showAlert(message) {
            const overlay = document.getElementById('alertOverlay');
            const alertText = overlay.querySelector('.alert-text');
            alertText.textContent = message;
            overlay.style.display = 'flex';
            
            setTimeout(() => {
                overlay.style.display = 'none';
            }, 2000);
        }

        // 更新SKU列表
        function updateSkuList() {
            const listContainer = document.getElementById('skuList');
            listContainer.innerHTML = Object.entries(scannedItems).map(([fnsku, data]) => `
                <div class="list-item">
                    <div>${fnsku}</div>
                    <div>${data.chineseSku}</div>
                    <div>${data.quantity}</div>
                </div>
            `).join('');
        }

        // 清空已扫描商品
        function clearScannedItems() {
            scannedItems = {};
            updateSkuList();
        }

        // 确认装箱
        function confirmBox() {
            if (!currentBoxCode) {
                showAlert('请先扫描箱码');
                return;
            }
            if (Object.keys(scannedItems).length === 0) {
                showAlert('请先扫描商品');
                return;
            }

            // 检查数量是否超出限制
            const totalQuantities = {};

            // 1. 计算当前箱子的数量
            Object.entries(scannedItems).forEach(([fnsku, data]) => {
                totalQuantities[fnsku] = (totalQuantities[fnsku] || 0) + data.quantity;
            });

            // 2. 加上其他箱子的数量
            planData.other_boxes.forEach(box => {
                box.sku_detail.forEach(detail => {
                    totalQuantities[detail.fnsku] = (totalQuantities[detail.fnsku] || 0) + detail.quantity;
                });
            });

            // 3. 加上已申请量
            Object.entries(planData.applied_quantities).forEach(([fnsku, quantity]) => {
                totalQuantities[fnsku] = (totalQuantities[fnsku] || 0) + quantity;
            });

            // 4. 检查是否超过下单量
            let isExceeded = false;
            let exceededSkus = [];

            planData.valid_skus.forEach(sku => {
                const total = totalQuantities[sku.fnsku] || 0;
                if (total > sku.order_quantity) {
                    isExceeded = true;
                    exceededSkus.push(sku.chinese_sku);
                }
            });

            if (isExceeded) {
                showAlert(`以下商品总量超过采购单下单量：\n${exceededSkus.join('\n')}`);
                return;
            }
            
            // TODO: 调用后端API保存装箱数据
            showAlert('装箱成功');
            setTimeout(() => {
                history.back();
            }, 1000);
        }

        // 箱码输入框事件监听
        document.getElementById('boxCodeInput').addEventListener('change', function(e) {
            const boxCode = e.target.value.trim();
            
            if (!validateBoxCode(boxCode)) {
                if (mode === 'repack') {
                    showAlert('箱码不属于该入库计划');
                } else {
                    showAlert('请使用空箱');
                }
                e.target.value = '';
                return;
            }

            currentBoxCode = boxCode;
            document.getElementById('currentBoxCode').textContent = boxCode;
            e.target.value = '';
        });

        // SKU输入框事件监听
        document.getElementById('skuInput').addEventListener('change', function(e) {
            const fnsku = e.target.value.trim();
            
            if (!currentBoxCode) {
                showAlert('请先扫描箱码');
                e.target.value = '';
                return;
            }

            if (!validateSku(fnsku)) {
                showAlert('商品不属于该采购单');
                e.target.value = '';
                return;
            }

            const chineseSku = getChineseSku(fnsku);
            if (scannedItems[fnsku]) {
                scannedItems[fnsku].quantity += 1;
            } else {
                scannedItems[fnsku] = {
                    chineseSku: chineseSku,
                    quantity: 1
                };
            }

            updateSkuList();
            e.target.value = '';
        });

        // 页面加载时初始化
        window.onload = initPage;
    </script>
</body>
</html> 